package com.example.demo.servier;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.example.demo.bojo.Book;

@Component
public class BookServiceImpl {

	// 定时交换器
	@Value("${queueConfig.delayExchangeName}")
	private String delayExchangeName;

	// 定时队列
	@Value("${queueConfig.delayQueueName}")
	private String delayQueueName;

	// @RabbitListener(queues = "atguigu.news")
	public void receive(Book book) {

		System.out.println("==============================================================");
		System.out.println("收到信息" + book);
		System.out.println("==============================================================");

	}

	@RabbitListener(queues = "atguigu.news")
	public void receive(Message m, Book book) {
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		System.out.println(s.format(new Date()));
		System.out.println(m.getBody());
		System.out.println(m.getMessageProperties());
		System.out.println(book);
		System.out.println(s.format(new Date()));

	}

	@Autowired
	private RabbitTemplate rabbitTemplate;

	// 发送信息
	public void sendMsg(String queueName, String msg) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		System.out.println("消息发送时间:" + sdf.format(new Date()));
		rabbitTemplate.convertAndSend("delayExchange", queueName, msg, new MessagePostProcessor() {
			@Override
			public Message postProcessMessage(Message message) throws AmqpException {
				message.getMessageProperties().setHeader("x-delay", 3000);
				return message;
			}
		});
	}

	// mq监听器
	@RabbitListener(queues = "delayQueue")
	public void receive(String msg) {
		System.out.println(delayExchangeName);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("1号消息接收时间:" + sdf.format(new Date()));
		System.out.println("接收到的消息:" + msg);
	}

	@RabbitListener(queues = "delayQueue")
	public void receive2(String msg) {
		System.out.println(delayExchangeName);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("2号消息接收时间:" + sdf.format(new Date()));
		System.out.println("接收到的消息:" + msg);

	}

}
